-- 游戏启动将自动运行此文件
local FrameLoader = require("Utils.FrameLoader")
local PrefabFactory = require("Utils.PrefabFactory")
local Consts = require("Data.Consts")
local UINodes = require("Data.UINodes")
local usedTiles = {}
local oxygens = {}

local ramainBombTime = {}
local skill1Level = {}
local isFly = {}
local waitSettle = {}
local flySpeed = 10
--- main.lua
require "ClassUtils"
local MathUtils = require("Utils.MathUtils")
local enhancementData = require("Data.TableEnhancement")

G = {}
G.frameLoader = FrameLoader.new(8, 1) -- 分帧加载器
G.prefabFactory = PrefabFactory.new()
G.tickables = {G.frameLoader}

G.coins = {}

local block = require("BlockManager")
local money = require("MoneyManager")
print("抽取结果")
print(block:generateBlock(300))

BASIC_OXYGEN = 100

-- 存储多个角色的技能数据
function addSkill(roleid, skillname)
    if type(skill1Level[roleid]) ~= "table" then
        skill1Level[roleid] = {}
    end
    skillname = skillname or "氧气增加"
    skill1Level[roleid][skillname] = (skill1Level[roleid][skillname] or 0) + 1
    return skill1Level[roleid][skillname]
end

LuaAPI.global_register_trigger_event({EVENT.GAME_END}, function()

    print("游戏结束")
end)
-- 掉落地面
LuaAPI.unit_register_trigger_event(GameAPI.get_unit(1681499584), {EVENT.SPEC_OBSTACLE_CONTACT_BEGIN},
    function(_, _, data)
        -- print("碰到地面")
        -- print(data)
        local roleId = data.unit2.get_role_id()

        -- jumpSettle(roleId)
    end)

function jumpSettle()
    if (waitSettle[roleId]) then
        print("跳高结算")
    end

    waitSettle[roleId] = false
    --  LuaAPI.unit_send_custom_event(data.unit2,"落地爆炸")
    GameAPI.create_sfx_with_socket(5189, data.unit2, Enums.ModelSocket.socket_foot_r, 0.3, 1.2,
        Enums.BindType.BIND_TYPE_DEFAULT)

    -- print("角色id:" .. data.unit2.get_role_id())
end

local gacha = require("GachaManager")

-- 单抽

LuaAPI.global_register_trigger_event({EVENT.GAME_INIT}, function()
    for _, role in ipairs(GameAPI.get_all_valid_roles()) do


        LuaAPI.global_register_trigger_event({ EVENT.SPEC_ROLE_PURCHASE_GOODS, role.get_roleid() }, function(_, _, data)
			-- 购买成功后刷新角色商城界面




            print("买好了")
            print(role)
			-- refresh_mall_panel(role)
		end)

        gacha:updateUI(role)

        local u = role.get_ctrl_unit()
        LuaAPI.global_register_trigger_event({EVENT.UI_CUSTOM_EVENT, "显示抽奖结果"},
            function(event_name, actor, data)
                print("动画结束xxxxxxx:")
                print(data.role_id)
                print(data.role)
                local role = data.role

                role.set_node_visible(UINodes["抽奖中宝箱"], false)
                role.set_node_visible(UINodes["抽奖结果弹窗"], true)
                role.set_node_visible(UINodes["抽奖商店"], false)
                local res = gacha:drawOnce()
                gacha:showResult(role, res)

            end)
    end

    RegisterGetCoinEvent()

    LuaAPI.global_register_custom_event("执行抽奖", function(name, unit, data)

        -- 检查 data 是否为空或无效
        if not data then
            print("data 为空")
            return
        end

        -- 使用 unit_id 作为备选
        if data.role_id then
            print("使用 unit_id:", data.role_id)
            local newLevel = addSkill(data.role_id, "氧气增加")
            print("强化后等级：" .. newLevel)
        end
        local role = GameAPI.get_role(data.role_id)
        role.show_tips("购买强化成功")
        local character = data.event_unit
        local card = gacha:drawOnce()
        gacha:showResult(role, card)

    end)

    LuaAPI.global_register_custom_event("强化_1", function(name, unit, data)

        -- 检查 data 是否为空或无效
        if not data then
            print("data 为空")
            return
        end

        -- 使用 unit_id 作为备选
        if data.role_id then
            print("使用 unit_id:", data.role_id)
            local newLevel = addSkill(data.role_id, "氧气增加")
            print("强化后等级：" .. newLevel)
        end
        local role = GameAPI.get_role(data.role_id)
        role.show_tips("购买强化成功")
        local character = data.event_unit
        -- UpdateEnhandUI(role)
        UpdataAllRoleUI()

    end)

    LuaAPI.global_register_custom_event("跳下", function(name, unit, data)
        print("当前unit,跳下---")
        print("=== 调试 data 结构 ===")

        -- 检查 data 是否为空或无效
        if not data then
            print("data 为空")
            return
        end
        print(data)
        -- 使用 unit_id 作为备选
        if data.role_id then
            isFly[data.role_id] = false
        end

    end)

    local region = LuaAPI.query_unit("通用触发区域2")

    LuaAPI.global_register_trigger_event({EVENT.ANY_LIFEENTITY_TRIGGER_SPACE, Enums.TriggerSpaceEventType.ENTER,
                                          region.get_id()}, function(name, actor, data)
        print("进入触发区域2")

        local character = data.event_unit
        local role = character.get_role()
        isFly[character.get_role_id()] = true
        waitSettle[character.get_role_id()] = true

        -- -- ModifyBombTime(roldId, -1)
        -- -- local role = GameAPI.get_role(self.character.get_role_id()) -- 获取角色对象
        -- role.set_node_visible(UINodes["强化弹窗"], true) -- 设置经验值进度条当前值
        -- role.set_label_text(UINodes["金币文本_1"], tostring(enhancementData.OxyGenAdd.Price)) -- 设置经验值进度条当前值

    end)

    local region = LuaAPI.query_unit("通用触发区域1")

    -- print("读取存档")
    function UpdateEnhandUI(role)
        local roldId = role.get_roleid()
        role.set_label_text(UINodes["金币文本_1"],
            tostring(GetPrice(enhancementData.OxyGenAdd.Price, skill1Level[roldId]))) -- 设置经验值进度条当前值

        role.set_label_text(UINodes["强化名称1"], tostring(enhancementData.OxyGenAdd.Name)) -- 设置经验值进度条当前值
        role.set_label_text(UINodes["强化名称2"], tostring(enhancementData.BombRangeAdd.Name)) -- 设置经验值进度条当前值
        role.set_label_text(UINodes["强化名称3"], tostring(enhancementData.BombPowerAdd.Name)) -- 设置经验值进度条当前值
        role.set_label_text(UINodes["强化名称4"], tostring(enhancementData.AutoRecoverAdd.Name)) -- 设置经验值进度条当前值
    end
    for _, role in ipairs(GameAPI.get_all_valid_roles()) do

        LuaAPI.unit_register_trigger_event(role.get_ctrl_unit(),
            {EVENT.SPEC_EQUIPMENT_ENTER_CHAR_SLOT, Enums.EquipmentSlotType.EQUIPPED}, function(event_name, actor, data)
                print("equip success")
                print(data.equipment)
                print(data.slot_type)
                print(data.owner)
            end)

    end
    LuaAPI.global_register_trigger_event({EVENT.SPEC_ROLE_PURCHASE_GOODS, role}, function(event_name, actor, data)
        print("buy item")
        print(data.role)
        print(data.goods_id)
    end)
    LuaAPI.global_register_trigger_event({EVENT.ANY_EQUIPMENT_CHANGE_SLOT}, function(event_name, actor, data)

        print("装备改变了")
        print(data.equipment)
        print(data.owner)
        print(data.old_slot_type)
        print(data.old_index)
        print(data.new_slot_type)
        print(data.new_index)
        doSomomn()
    end)

    LuaAPI.global_register_trigger_event({EVENT.ANY_LIFEENTITY_TRIGGER_SPACE, Enums.TriggerSpaceEventType.ENTER,
                                          region.get_id()}, function(name, actor, data)
        print("进入触发区域！")
        --   local roldId = role.get_roleid()
        -- local u.get_role_id() 
        local character = data.event_unit
        local role = character.get_role()

        -- ModifyBombTime(roldId, -1)
        -- local role = GameAPI.get_role(self.character.get_role_id()) -- 获取角色对象
        role.set_node_visible(UINodes["强化弹窗"], true) -- 设置经验值进度条当前值
        UpdateEnhandUI(role)

    end)
    for _, role in ipairs(GameAPI.get_all_valid_roles()) do
        -- 获取角色控制的单位
        local character = role.get_ctrl_unit()
        --    character.set_equipment_max_count(EquipmentSlotType.Storage, 10)  -- 设置储物区最大槽位数为10
        local roldId = role.get_roleid()
        -- print("获取背包")

        -- print(character.get_equipment_list(Enums.EquipmentType.BASIC, false,false))
        --      LuaAPI.unit_register_trigger_event(character, { EVENT.SPEC_COMMODITY_CONSUME }, function(_, _, data)
        -- 	print("消耗物品")
        --     print(data)

        -- end)

        ramainBombTime[role.get_roleid()] = 10
        skill1Level[roldId] = 0
        -- 创建新的英雄对象
        -- add_attr_bonus_fixed(role,"coin_count",5.0)

        oxygens[roldId] = BASIC_OXYGEN
        G.coins[roldId] = 5000
    end
    local triggerId = nil

    local function _timerFunc(eventName, actor, data)
        money.updateMoneyUI()
        for _, role in ipairs(GameAPI.get_all_valid_roles()) do
            -- 获取角色控制的单位
            local character = role.get_ctrl_unit()
            local roldId = role.get_roleid()
            role.set_label_text(UINodes["金币文本"], tostring(math.tofixed(G.coins[roldId])))

            ramainBombTime[role.get_roleid()] = 10
            -- 创建新的英雄对象
            if (oxygens[roldId] > 0) then
                oxygens[roldId] = oxygens[roldId] - 1
                UpdataAllRoleUI()
            else
                isGrond = true
                player_die(roldId)
                return_to_ground(character)
            end

        end
    end
    triggerId = LuaAPI.global_register_trigger_event({EVENT.REPEAT_TIMEOUT, 1.0}, _timerFunc)
    UpdataAllRoleUI()
end)

function player_die(roleId)
    if G.coins[roleId] then
        G.coins[roleId] = G.coins[roleId] * 0.7 -- 保留70%，即减少30%
    end
end

function add_attr_bonus_fixed(role, key, value)
    local old_value = role.get_attr_bonus_fixed(key) or 0 -- Default to 0 if nil

    local new_value = old_value + value
    print("旧：" .. old_value .. "新:" .. new_value)
    -- Update the attribute bonus
    role.change_attr_bonus_fixed(key, new_value)
    -- Return the updated value
    return new_value
end

function doSomomn(unit)
    local equipment_list = unit.get_equipment_list(Enums.EquipmentType.BASIC, false, true)
    print(equipment_list)
    for _, equipment in ipairs(equipment_list) do
        local equipment_key = equipment:get_key()
        local extra_attr = AttrComp.get_attr_base_extra_fixed("生物id") -- 假设"生物id"是存储的额外属性名
        print(extra_attr)
    end
end

LuaAPI.global_register_trigger_event({EVENT.CUSTOM_EVENT, "组件破坏了"}, function(name, unit, data)
    print("组件破坏了")
    print(unit)
    print(data)

end)

LuaAPI.global_register_trigger_event({EVENT.CUSTOM_EVENT, "打开商店"}, function(name, unit, data)
    print("收到了 嘿嘿! test distance，尝试获取roleId" .. "钱:" .. G.coins[data.role_id])
 role.show_goods_purchase_panel("1073774713", 5.0)
    if data.role_id then
        print("角色 打开了商店")
        role = GameAPI.get_role(data.role_id)
        for _, role in ipairs(GameAPI.get_all_valid_roles()) do
            LuaAPI.global_register_trigger_event({ EVENT.SPEC_ROLE_PURCHASE_GOODS, role.get_roleid() }, function(_, _, data)
			-- 购买成功后刷新角色商城界面
			print("buy something")
		end)
            -- 获取角色控制的单位
            local character = role.get_ctrl_unit()

            local roldId = role.get_roleid()
            print("获取背包")

            print(character.get_equipment_list(Enums.EquipmentType.BASIC, false, false))
            print(character.get_equipment_list(Enums.EquipmentType.WEAPON, false, false))
            --      LuaAPI.unit_register_trigger_event(character, { EVENT.SPEC_COMMODITY_CONSUME }, function(_, _, data)
            -- 	print("消耗物品")
            --     print(data)

            -- end)

        end
        -- role.set_attr_bonus_fixed(Consts.CoinType.Gold, G.coins[data.role_id])
    end

end)

-- LuaAPI.unit_send_custom_event(GameAPI.get_all_valid_roles()[0],{EVENT.CUSTOM_EVENT, "打开强化弹窗"})

LuaAPI.global_register_trigger_event({EVENT.CUSTOM_EVENT, "炸弹释放完毕"}, function(name, unit, data)
    print("收到了 嘿嘿! test distance，尝试获取roleId")
    local character = data.event_unit
    local role = character.get_role()
    print("角色")
    print(role)
    -- self.setLevel(self.level) -- 设置初始等级
    -- role.set_progressbar_current(UINodes["经验值"], self.exp) -- 设置经验值进度条当前值
    -- role.set_progressbar_max(UINodes["经验值"], self:getLevelUpExp()) -- 设置经验值进度条最大值

end)

-- 更新所有角色ui
function UpdataAllRoleUI()
    for _, role in ipairs(GameAPI.get_all_valid_roles()) do
        local u = role.get_ctrl_unit()

        local roldId = role.get_roleid()
        ModifyBombTime(roldId, -1)

        role.set_label_text(UINodes["剩余炸弹数_文本"], tostring(ramainBombTime[roldId])) -- 设置经验值进度条当前值
        role.set_progressbar_max(UINodes["剩余氧气进度条"], calculateMaxOxygen(roldId))
        role.set_progressbar_current(UINodes["剩余氧气进度条"], oxygens[roldId])

    end
end

function calculateMaxOxygen(roleid)

    local skillLevel = 0

    if skill1Level[roleid] and type(skill1Level[roleid]) == "table" then
        skillLevel = skill1Level[roleid]["氧气增加"] or 0
    end

    local levelAdd = enhancementData.OxyGenAdd.LevelAdd or 0
    return BASIC_OXYGEN + skillLevel * levelAdd
end

-- 统一的增减函数
function ModifyBombTime(roleId, value)
    if not ramainBombTime[roleId] then
        ramainBombTime[roleId] = 3
    end
    ramainBombTime[roleId] = ramainBombTime[roleId] + value
    return ramainBombTime[roleId]
end
-- 价格公式
function GetPrice(base, level)
    return math.floor(base * (1.6 ^ level))
end

-- 矿石掉落
local OreDrop = {
    Common = {2, 5}, -- 90%
    Uncommon = {12, 25}, -- 8%
    Rare = {60, 120}, -- 1.8%
    Epic = {300, 700} -- 0.2%
}

-- 氧气
local Oxygen = {
    Max = 300,
    PerBomb = 25
}

-- 强化配置
local Upgrades = {
    OxyGenAdd = {
        Name = "氧气增加",
        Base = 180,
        Add = 30
    },
    BombPowerAdd = {
        Name = "炸弹威力",
        Base = 250,
        Add = 15
    },
    BombRangeAdd = {
        Name = "爆炸范围",
        Base = 280,
        Add = 12
    },
    DigSpeedAdd = {
        Name = "挖掘速度",
        Base = 220,
        Add = 20
    },
    DropRateAdd = {
        Name = "矿石掉落",
        Base = 350,
        Add = 10
    },
    AutoRecoverAdd = {
        Name = "自动回氧",
        Base = 150,
        Add = 10
    }
}
function RegisterGetCoinEvent()
    for _, role in ipairs(GameAPI.get_all_valid_roles()) do
        local u = role.get_ctrl_unit()

        LuaAPI.unit_register_trigger_event(u, {EVENT.CUSTOM_EVENT, "动画结束"}, function(name, actor, data)

            print("动画结束:")

            local roldId = role.get_roleid()
            -- local u.get_role_id() 
            print("角色id" .. roldId)

        end)

        LuaAPI.unit_register_trigger_event(u, {EVENT.CUSTOM_EVENT, "获得金币"}, function(name, actor, data)

            print("获得金币:")

            local roldId = role.get_roleid()
            print("角色id" .. roldId)
            G.coins[roldId] = G.coins[roldId] + 4; -- 3-5
            -- add_attr_bonus_fixed(role,"coin_count",50.0)

        end)
    end
end

function return_to_ground(unit)
    local target = GameAPI.get_unit(2093668018)
    unit.set_position(target.get_position())
end

for _, role in ipairs(GameAPI.get_all_valid_roles()) do
    local u = role.get_ctrl_unit()
    -- u.add_ability_to_slot(2,10047);

    local roldId = role.get_roleid()
    isFly[roldId] = false

    LuaAPI.unit_register_trigger_event(u, {EVENT.CUSTOM_EVENT, "加氧气"}, function(name, actor, data)

        print("加氧气拉，找到实体,hahahah")

        roldId = role.get_roleid()
        -- local u.get_role_id() 
        print("角色id" .. roldId)
        -- local role = GameAPI.get_role(self.character.get_role_id()) -- 获取角色对象

    end)
    LuaAPI.unit_register_trigger_event(u, {EVENT.CUSTOM_EVENT, "回地面"}, function(name, actor, data)

       
        local target = GameAPI.get_unit(2093668018)
        print("找到实体,hahahah")

        roldId = role.get_roleid()
        -- local u.get_role_id() 
        print("角色id" .. roldId)
        ModifyBombTime(roldId, -1)
        -- local role = GameAPI.get_role(self.character.get_role_id()) -- 获取角色对象

        role.set_label_text(UINodes["剩余炸弹数_文本"], tostring(ramainBombTime[roldId])) -- 设置经验值进度条当前值

        print(target)

    end)

    LuaAPI.unit_register_trigger_event(u, {EVENT.CUSTOM_EVENT, "打开背包"}, function(name, actor, data)

        print("openbag11:")

        roldId = role.get_roleid()
        -- local u.get_role_id() 
        print("角色id" .. roldId)

    end)

    LuaAPI.global_register_trigger_event({EVENT.UI_CUSTOM_EVENT, "动画结束"}, function(event_name, actor, data)
        print("动画结束xxxxxxx:")
        print(data.role_id)
        print(data.role)
        local role = data.role
        --  role.send_ui_custom_event("停止动画", nil)
        role.set_ui_opacity(UINodes["蛋仔宝箱"], 0.0)
        -- print(data.eui_node_id)
    end)

    --  LuaAPI.global_register_custom_event({EVENT.CUSTOM_EVENT, "动画结束"}, function(name, actor, data)

    --     print("动画结束:")

    --     roldId = role.get_roleid()
    --     -- local u.get_role_id() 
    --     print("角色id" .. roldId)

    -- end)

    LuaAPI.global_register_trigger_event({EVENT.CUSTOM_EVENT, "打开背包"}, function(name, actor, data)

        print("openbag22:")

        roldId = role.get_roleid()
        -- local u.get_role_id() 
        print("角色id" .. roldId)

    end)
    -- 获取角色控制的单位
    -- local character = role.get_ctrl_unit()
    -- -- 创建新的英雄对象
    -- character.set_position(target.get_position()+math.Vector3(0,2,0))
    -- local a = GameAPI.create_creature_fixed_scale(9000080,target.get_position()+math.Vector3(0,4,0));
end

-- 注册方块并绑定销毁事件
function registerBlock(unit, x, y, z)
    if not unit then
        return
    end

end

function restoreDestroyedBlocks()
    print("开始恢复被销毁的方块，数量:", table.size(destroyedBlocks))

    for posKey, originalPos in pairs(destroyedBlocks) do
        G.prefabFactory:createPrefabWithCb(Consts.PrefabType.UNIT_OBSTACLE, 1073741892,
            math.Vector3(originalPos.x, originalPos.y, originalPos.z), math.Quaternion(0, 0, 0), math.Vector3(2, 2, 2),
            function(unit)
                registerBlock(unit, originalPos.x, originalPos.y, originalPos.z)
            end)
        print("恢复方块位置:", posKey)
    end

    -- 清空记录
    destroyedBlocks = {}
end

function G.addTickable(obj)
    assert(obj.update)
    table.insert(G.tickables, obj)
end

-- 移除可更新对象的函数
function G.removeTickable(obj)
    for i, v in ipairs(G.tickables) do
        if v == obj then
            table.remove(G.tickables, i)
            break
        end
    end
end

-- 获取目标方块（假设方块名为"目标方块"）
local targetBlock = LuaAPI.query_unit("方块-可变形6")
local blockPos = targetBlock.get_position()
local blockMinY = blockPos.y - 50 -- 假设方块中心在中间
local blockMaxY = blockPos.y + 50

-- 计算相对于方块高度的百分比
local percentage = 0
local blockHeight = 30
-- 定义每帧更新前的处理函数
local function onPreTick(_)
    for k, v in ipairs(isFly) do
        if (v) then
            print("roleid:" .. k)
            local playerY = GameAPI.get_role(k).get_ctrl_unit().get_position().y
            print("玩家y: " .. playerY)
            percentage = playerY / blockHeight * 100
            print("玩家y位置百分比: " .. percentage .. "%")
            GameAPI.get_role(k).get_ctrl_unit().set_linear_velocity(math.Vector3(0, flySpeed, 0))

        end
    end
    for _, v in ipairs(G.tickables) do
        v:update()
    end
end

-- 定义每帧更新后的处理函数（当前为空）
local function onPostTick()
end

-- 设置帧更新处理器
LuaAPI.set_tick_handler(onPreTick, onPostTick)

-- local gacha = require("GachaManager")

-- print("抽取结果")
-- print(gacha.drawOnce())

-- print(gacha.drawOnce())

-- print(gacha.drawOnce())

-- print(gacha.drawOnce())
-- print(gacha.drawOnce())
